package org.yray.tts.media;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class ByteBuf {

    private byte[][] bss;
    private AtomicInteger index;
    private AtomicInteger len;

    public void addBytes(byte[] bs,int begin,int byteLen)
    {
        if(bss==null)
        {
            bss=new byte[1000][];
            index=new AtomicInteger(0);
            len=new AtomicInteger(0);
        }
        len.addAndGet(byteLen);
        byte[] bytes=new byte[byteLen];
        System.arraycopy(bs,begin,bytes,0,byteLen);
        bss[index.getAndIncrement()]=bytes;
    }

    public byte[] toBytes()
    {
        byte[] result=new byte[len.get()];
        int pos=0;
        for(int i=0;i<index.get();i++)
        {
            System.arraycopy(bss[i],0,result,pos,bss[i].length);
            pos+=bss[i].length;
        }
        return result;
    }

    public byte[] toBytesAlign()
    {
        //按160个字节对齐
        int alignLen= + (160-len.get()%160);
        byte[] result=new byte[len.get()+alignLen];
        int pos=0;
        for(int i=0;i<index.get();i++)
        {
            System.arraycopy(bss[i],0,result,pos,bss[i].length);
            pos+=bss[i].length;
        }
        if(alignLen>0) {
            for(int i=0;i<alignLen;i++)
            {
                result[result.length-i-1]=0;
            }
        }
        return result;
    }
}
